package com.itfreer.map;

import android.app.Fragment;
import android.Manifest;
import android.app.FragmentTransaction;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.view.WindowManager;

import com.itfreer.content.task.TaskActivity;
import com.itfreer.gis.api.IMap;
import com.itfreer.gis.api.ISearch;
import com.itfreer.gis.styles.StyleService;
import com.itfreer.gis.ui.control.CentreControl;
import com.itfreer.gis.ui.control.DrawControl;
import com.itfreer.gis.ui.control.EditControl;
import com.itfreer.gis.ui.control.LocalControl;
import com.itfreer.gis.ui.control.MenuControl;
import com.itfreer.gis.ui.control.NaviControl;
import com.itfreer.gis.ui.control.SearchControl;
import com.itfreer.gis.ui.control.ToolsControl;
import com.itfreer.map.jtjs.gh.GhAfGcFragment;
import com.itfreer.map.jtjs.gh.GhBjlFragment;
import com.itfreer.map.jtjs.gh.GhGlFragment;
import com.itfreer.map.jtjs.gh.GhLhGcFragment;
import com.itfreer.map.jtjs.gh.GhQlFragment;
import com.itfreer.map.jtjs.gh.GhQtFragment;
import com.itfreer.map.jtjs.gh.GhShncFragment;
import com.itfreer.map.jtjs.gh.GhXxbyFragment;
import com.itfreer.map.jtjs.gh.GhZhGcFragment;
import com.itfreer.map.jtjs.gh.GhZljkFragment;
import com.itfreer.map.jtjs.jc.JcLxFragment;
import com.itfreer.map.jtjs.jc.JcQlFragment;
import com.itfreer.setting.ui.SettingActivity;
import com.itfreer.ui.activity.BaseActivity;
import com.itfreer.core.config.ConfigManager;
import com.itfreer.content.notice.MessageActivity;
import com.itfreer.core.collection.SerializableMap;

import java.util.List;

import androidx.annotation.RequiresApi;
import androidx.core.app.ActivityCompat;

/**
 * 主界面，全屏展示
 */
public class MainActivity extends BaseActivity {

    // Fragment
    private Fragment fragment;
    // 查询框控件
    private SearchControl searchControl;
    // 地图工具
    private ToolsControl toolsControl;
    // 导航工具
    private NaviControl naviControl;
    // 定位工具
    private LocalControl localControl;
    // 绘制工具
    private DrawControl drawControl;
    // 中心点
    private CentreControl centreControl;
    // 编辑框
    private EditControl editControl;
    // 底部菜单工具
    private MenuControl menuControl;

    // 地图view
    private IMap mapView;

    private static final int REQUEST_CODE = 10;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // 防止休眠
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON, WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);

        // 设置容器
        setContentView(R.layout.main_activity);

        // 地图初始化
        mapView = findViewById(R.id.mapView);
        // 查询框控件
        searchControl = findViewById(R.id.searchControl);
        // 地图工具
        toolsControl = findViewById(R.id.toolsControl);
        // 导航工具
        naviControl = findViewById(R.id.naviControl);
        // 定位工具
        localControl = findViewById(R.id.localControl);
        // 绘制工具
        drawControl = findViewById(R.id.drawControl);
        // 中心点
        centreControl = findViewById(R.id.centreControl);
        // 编辑框
        editControl = findViewById(R.id.editControl);
        // 底部菜单工具
        menuControl = findViewById(R.id.menuControl);

        // 初始化配置
        mapView.onCreate(savedInstanceState);
        ConfigManager.setConfig("map", mapView);
        ConfigManager.setContext(this);
        mapView.init();

        // 初始化控件
        searchControl.setMeOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                // 新建一个Intent对象
                Intent intent = new Intent();
                // 将map数据添加到封装的myMap中
                final SerializableMap dataMap = new SerializableMap();
                dataMap.setMap(null);
                Bundle bundle = new Bundle();
                bundle.putSerializable("map", dataMap);
                intent.putExtras(bundle);
                // 指定intent要启动的类
                intent.setClass(MainActivity.this, SettingActivity.class);
                // 启动一个新的Activity
                startActivityForResult(intent, 1);
            }
        });
        searchControl.setMsgOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                // 新建一个Intent对象
                Intent intent = new Intent();
                // 将map数据添加到封装的myMap中
                final SerializableMap dataMap = new SerializableMap();
                dataMap.setMap(null);
                Bundle bundle = new Bundle();
                bundle.putSerializable("map", dataMap);
                intent.putExtras(bundle);
                // 指定intent要启动的类
                intent.setClass(MainActivity.this, MessageActivity.class);
                // 启动一个新的Activity
                startActivityForResult(intent, 2);
            }
        });
        // 地图工具
        toolsControl.setContainerViewId(R.id.fragment);
        // 控件间关联关系
        menuControl.setEditControl(editControl);
        menuControl.setToolsControl(toolsControl);
        menuControl.setLeftMenuOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                // 新建一个Intent对象
                Intent intent = new Intent();
                // 将map数据添加到封装的myMap中
                final SerializableMap dataMap = new SerializableMap();
                dataMap.setMap(null);
                Bundle bundle = new Bundle();
                bundle.putSerializable("map", dataMap);
                intent.putExtras(bundle);
                // 指定intent要启动的类
                intent.setClass(MainActivity.this, MessageActivity.class);
                // 启动一个新的Activity
                startActivityForResult(intent, 2);
            }
        });
        menuControl.setRightMenuOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                // 新建一个Intent对象
                Intent intent = new Intent();
                // 将map数据添加到封装的myMap中
                final SerializableMap dataMap = new SerializableMap();
                dataMap.setMap(null);
                Bundle bundle = new Bundle();
                bundle.putSerializable("map", dataMap);
                intent.putExtras(bundle);
                // 指定intent要启动的类
                intent.setClass(MainActivity.this, TaskActivity.class);
                // 启动一个新的Activity
                startActivityForResult(intent, 4);
            }
        });
        editControl.setMenuControl(menuControl);
        editControl.setDrawControl(drawControl);
        editControl.setToolsControl(toolsControl);
        editControl.setCentreControl(centreControl);
        editControl.setSearchControl(searchControl);

        // android6 执行运行时权限
        if (Build.VERSION.SDK_INT >= 23) {
            if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED ||
                    ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED ||
                    ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED ||
                    ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(this, new String[]{
                        Manifest.permission.READ_EXTERNAL_STORAGE,
                        Manifest.permission.WRITE_EXTERNAL_STORAGE,
                        Manifest.permission.ACCESS_FINE_LOCATION,
                        Manifest.permission.ACCESS_COARSE_LOCATION}, REQUEST_CODE);
            }
        }

        // 处理查询事项
        ISearch search = (ISearch)ConfigManager.getConfig("ISearch");
        search.setSearchOnFindFeature(new ISearch.OnFindFeature() {
            @Override
            public void onFind(StyleService.SelectLayer layer, Object feature) {
                // 规划-公路 1
                if(layer.getSourceid().equals("jtjs_gh_gl")) {
                    GhGlFragment ghGlFragment = new GhGlFragment();
                    ghGlFragment.setData("jtjs_gh_gl", feature);
                    startFragment(ghGlFragment);
                } else if(layer.getSourceid().equals("jtjs_gh_shncgl")) {
                    // 四好农村公路 2
                    GhShncFragment ghGlFragment = new GhShncFragment();
                    ghGlFragment.setData("jtjs_gh_shncgl", feature);
                    startFragment(ghGlFragment);
                } else if(layer.getSourceid().equals("jtjs_gh_bjl")) {
                    // 边界路、断头路 3
                    GhBjlFragment ghGlFragment = new GhBjlFragment();
                    ghGlFragment.setData("jtjs_gh_bjl", feature);
                    startFragment(ghGlFragment);
                } else if(layer.getSourceid().equals("jtjs_gh_zljkgl")) {
                    // 窄路加宽公路 4
                    GhZljkFragment ghGlFragment = new GhZljkFragment();
                    ghGlFragment.setData("jtjs_gh_zljkgl", feature);
                    startFragment(ghGlFragment);
                } else if(layer.getSourceid().equals("jtjs_gh_xxbygl")) {
                    // 5/小修保养公路
                    GhXxbyFragment ghGlFragment = new GhXxbyFragment();
                    ghGlFragment.setData("jtjs_gh_xxbygl", feature);
                    startFragment(ghGlFragment);
                } else if(layer.getSourceid().equals("jtjs_gh_ql")) {
                    // 6/桥梁    JTJS_GH_QL
                    GhQlFragment ghGlFragment = new GhQlFragment();
                    ghGlFragment.setData("jtjs_gh_ql", feature);
                    startFragment(ghGlFragment);
                } else if(layer.getSourceid().equals("jtjs_gh_zhgc")) {
                    // 7/灾毁工程公路    JTJS_GH_ZHGC
                    GhZhGcFragment ghGlFragment = new GhZhGcFragment();
                    ghGlFragment.setData("jtjs_gh_zhgc", feature);
                    startFragment(ghGlFragment);
                } else if(layer.getSourceid().equals("jtjs_gh_afgc")) {
                    // 8/安防工程  JTJS_GH_AFGC
                    GhAfGcFragment ghGlFragment = new GhAfGcFragment();
                    ghGlFragment.setData("jtjs_gh_afgc", feature);
                    startFragment(ghGlFragment);
                } else if(layer.getSourceid().equals("jtjs_gh_lhgc")) {
                    // 9/绿化工程  JTJS_GH_LHGC
                    GhLhGcFragment ghGlFragment = new GhLhGcFragment();
                    ghGlFragment.setData("jtjs_gh_afgc", feature);
                    startFragment(ghGlFragment);
                } else if(layer.getSourceid().equals("jtjs_gh_qt")) {
                    // 10/其他   JTJS_GH_QT
                    GhQtFragment ghGlFragment = new GhQtFragment();
                    ghGlFragment.setData("jtjs_gh_qt", feature);
                    startFragment(ghGlFragment);
                } else if(layer.getSourceid().equals("jtjs_jc_lx")) {
                    // 基础路线数据
                    JcLxFragment ghGlFragment = new JcLxFragment();
                    ghGlFragment.setData("jtjs_jc_lx", feature);
                    startFragment(ghGlFragment);
                } else if(layer.getSourceid().equals("jtjs_jc_ql")) {
                    // 基础桥梁数据
                    JcQlFragment ghGlFragment = new JcQlFragment();
                    ghGlFragment.setData("jtjs_jc_ql", feature);
                    startFragment(ghGlFragment);
                }
            }

            @Override
            public void onUnFind() {
            }
        });
    }

    private void startFragment(Fragment fragment) {
        FragmentManager.popBackStack();
        FragmentTransaction ft2 = this.getFragmentManager().beginTransaction();
        ft2.replace(R.id.fragment, fragment);
        ft2.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
        ft2.addToBackStack(null);
        ft2.commit();
    }

    @RequiresApi(api = Build.VERSION_CODES.O)
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        // 按下键盘上返回按钮
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            List<Fragment> fragments = this.getFragmentManager().getFragments();
            if(fragments==null || fragments.size()<=1){
                return super.onKeyDown(keyCode, event);
            } else {
                FragmentManager.popBackStack();
                return true;
            }

        } else {
            return super.onKeyDown(keyCode, event);
        }
    }

    /**
     * 返回时，是否可以退出
     *
     * @return
     */
    @Override
    protected boolean canExit() {
        return true;
    }

    @Override
    protected void onStart() {
        super.onStart();
        mapView.onStart();
    }

    @Override
    protected void onResume() {
        super.onResume();
        mapView.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
        mapView.onPause();
    }

    @Override
    protected void onStop() {
        super.onStop();
        mapView.onStop();
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        mapView.onSaveInstanceState(outState);
    }

    @Override
    public void onLowMemory() {
        super.onLowMemory();
        mapView.onLowMemory();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mapView.onDestroy();
    }

    /**
     * 获取权限结果
     */
    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == REQUEST_CODE) {
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                // Permission Granted准许
            } else {
                // Permission Denied拒绝
            }
        }
    }
}